<template>
  <el-row :gutter="0">
    <el-col :span="6" style="margin-top: 15px"
      ><div class="grid-content bg-purple">
        <Category @tree-node-click="handleTreeNodeClick"></Category></div
    ></el-col>
    <el-col :span="18"
      ><div class="grid-content bg-purple">
        <div class="app-container">
          <el-form
            :model="queryParams"
            ref="queryForm"
            size="small"
            :inline="true"
            v-show="showSearch"
            label-width="68px"
          >
            <el-form-item label="所属分类" prop="catelogId">
              <el-cascader
                placeholder="请选择所属分类"
                v-model="queryParams.catelogPath"
                :options="categoryList"
                :props="cateprops"
                @keyup.enter.native="handleQuery"
              ></el-cascader>
            </el-form-item>
            <el-form-item label="属性名" prop="attrName">
              <el-input
                v-model="queryParams.attrName"
                placeholder="请输入属性名"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item label="启用状态" prop="enable">
              <el-input
                v-model="queryParams.enable"
                placeholder="请输入启用状态"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>

            <el-form-item>
              <el-button
                type="primary"
                icon="el-icon-search"
                size="mini"
                @click="handleQuery"
                >搜索</el-button
              >
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
                >重置</el-button
              >
            </el-form-item>
          </el-form>

          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button
                type="primary"
                plain
                icon="el-icon-plus"
                size="mini"
                @click="handleAdd"
                v-hasPermi="['cloudmallproduct:productAttr:add']"
                >新增</el-button
              >
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="success"
                plain
                icon="el-icon-edit"
                size="mini"
                :disabled="single"
                @click="handleUpdate"
                v-hasPermi="['cloudmallproduct:productAttr:edit']"
                >修改</el-button
              >
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="danger"
                plain
                icon="el-icon-delete"
                size="mini"
                :disabled="multiple"
                @click="handleDelete"
                v-hasPermi="['cloudmallproduct:productAttr:remove']"
                >删除</el-button
              >
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="warning"
                plain
                icon="el-icon-download"
                size="mini"
                @click="handleExport"
                v-hasPermi="['cloudmallproduct:productAttr:export']"
                >导出</el-button
              >
            </el-col>
            <el-col :span="2" style="text-align: right">
              <!-- 切换分类显示方式的按钮 -->
              <el-button
                type="primary"
                size="mini"
                @click="toggleCategoryDisplay"
              >
                {{ showFullPath ? "显示末级分类" : "显示完整路径" }}
              </el-button>
            </el-col>
            <right-toolbar
              :showSearch.sync="showSearch"
              @queryTable="getList"
            ></right-toolbar>
          </el-row>

          <el-table
            v-loading="loading"
            :data="productAttrList"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column type="index" label="序号" align="center">
              <template #default="{ $index }">
                {{
                  queryParams.pageNum * queryParams.pageSize -
                  queryParams.pageSize +
                  $index +
                  1
                }}
              </template>
            </el-table-column>

            <el-table-column
              label="属性名"
              align="center"
              width="130"
              prop="attrName"
            />
            <el-table-column label="可检索" align="center" prop="searchType">
              <!-- 作用域插槽，获取当前行数据 row -->
              <template #default="{ row }">
                <span v-if="row.searchType === 0">
                  <i class="el-icon-close"></i>
                </span>
                <span v-if="row.searchType === 1">
                  <i class="el-icon-check"></i>
                </span>
              </template>
            </el-table-column>
            <el-table-column label="值类型" align="center" prop="valueType">
              <template #default="{ row }">
                <el-tag v-if="row.valueType === 0" type="success">单选</el-tag>
                <el-tag v-else type="warning">多选</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="属性图标" align="center" prop="icon" />
            <el-table-column label="可选项" align="center" prop="valueSelect">
              <template #default="{ row }">
                <div class="value-select-cell">
                  {{ row.valueSelect }}
                </div>
              </template>
            </el-table-column>
            <el-table-column label="属性类型" align="center" prop="attrType">
              <template #default="{ row }">
                <el-tag v-if="row.attrType === 0" type="success"
                  >销售属性</el-tag
                >
                <el-tag v-else type="warning">基本属性</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="所属分类" align="center" prop="catelogId">
              <template #default="{ row }">
                {{
                  showFullPath ? getCategoryFullPath(row) : getCategoryName(row)
                }}
              </template>
            </el-table-column>
            <el-table-column label="启用状态" align="center" prop="enable">
              <template #default="{ row }">
                <el-switch
                  v-model="row.enable"
                  :active-value="1"
                  :inactive-value="0"
                  active-color="#ff4949"
                  inactive-color="#13ce66"
                  @change="handleEnableChange(row)"
                ></el-switch>
              </template>
            </el-table-column>
            <el-table-column label="介绍展示" align="center" prop="showDesc">
              <template #default="{ row }">
                <el-switch
                  v-model="row.showDesc"
                  :active-value="1"
                  :inactive-value="0"
                  active-color="#ff4949"
                  inactive-color="#13ce66"
                  @change="handleshowDescChange(row)"
                ></el-switch>
              </template>
            </el-table-column>
            <el-table-column
              label="操作"
              align="center"
              class-name="small-padding fixed-width"
            >
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click="handleUpdate(scope.row)"
                  v-hasPermi="['cloudmallproduct:productAttr:edit']"
                  >修改</el-button
                >
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="handleDelete(scope.row)"
                  v-hasPermi="['cloudmallproduct:productAttr:remove']"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>

          <pagination
            v-show="total > 0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
          />

          <!-- 添加或修改商品属性对话框 -->
          <el-dialog
            :title="title"
            :visible.sync="open"
            width="500px"
            append-to-body
          >
            <el-form ref="form" :model="form" :rules="rules" label-width="80px">
              <el-form-item label="属性名" prop="attrName">
                <el-input v-model="form.attrName" placeholder="请输入属性名" />
              </el-form-item>
              <el-form-item label="属性类型" prop="attrType">
                <!-- 下拉选择器：绑定表单值form.attrType，禁用空选 -->
                <el-select
                  v-model="form.attrType"
                  placeholder="请选择属性类型"
                  required
                >
                  <!-- 基础属性：value设为1（对应后端接收的1） -->
                  <el-option label="规格参数" :value="1"> 规格参数</el-option>
                  <!-- 销售属性：value设为0（对应后端接收的0） -->
                  <el-option label="销售属性" :value="0"> 销售属性</el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="属性图标" prop="icon">
                <el-input v-model="form.icon" placeholder="请输入属性图标" />
              </el-form-item>
              <el-form-item label="值类型">
                <el-radio
                  v-model="form.valueType"
                  label="单选"
                  @change="handleValueTypeChange"
                  >单选项</el-radio
                >
                <el-radio
                  v-model="form.valueType"
                  label="多选"
                  @change="handleValueTypeChange"
                  >多选项</el-radio
                >
              </el-form-item>
              <el-form-item label="可选项">
                <!-- 输入框：实时监听输入，按回车/失去焦点时添加选项 -->
                <el-input
                  v-model="tempInput"
                  placeholder="输入选项值"
                  @keyup.enter.native="addOption"
                  @blur="addOption"
                />

                <!-- 动态渲染已添加的选项 -->
                <div class="option-list">
                  <el-tag
                    v-for="(option, index) in valueOptions"
                    :key="index"
                    closable
                    @close="removeOption(index)"
                  >
                    {{ option }}
                  </el-tag>
                </div>
              </el-form-item>

              <el-form-item label="所属分类" prop="catelogId">
                <el-cascader
                  placeholder="请选择所属分类"
                  v-model="form.catelogId"
                  :options="categoryList"
                  :props="cateprops"
                ></el-cascader>
              </el-form-item>
              <el-form-item label="介绍展示" prop="searchType">
                <el-switch
                  v-model="form.searchType"
                  :active-value="1"
                  :inactive-value="0"
                  active-color="#ff4949"
                  inactive-color="#13ce66"
                ></el-switch>
              </el-form-item>
              <el-form-item label="启用状态" prop="enable">
                <el-switch
                  v-model="form.enable"
                  :active-value="1"
                  :inactive-value="0"
                  active-color="#ff4949"
                  inactive-color="#13ce66"
                ></el-switch>
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button type="primary" @click="submitForm">确 定</el-button>
              <el-button @click="cancel">取 消</el-button>
            </div>
          </el-dialog>
        </div>
      </div></el-col
    >
  </el-row>
</template>

<script>
import {
  listProductAttr,
  getProductAttr,
  delProductAttr,
  addProductAttr,
  updateProductAttr,
} from "@/api/product/attrSale";
import Category from "@/components/category";
import { listWithTree } from "@/api/product/category";
import { listSaleAttr } from "@/api/product/attrSale";

export default {
  name: "ProductAttr",
  components: {
    Category,
  },
  data() {
    return {
      // 存储最终的可选项列表（数组）
      valueOptions: [],
      // 绑定输入框的临时值
      tempInput: "",
      // 标记当前是否为“单选”模式（true：单选，false：多选）
      isSingle: true,
      // 当前分类完成路径
      catelogPath: [],
      // 所有分类
      categoryList: [],
      cateprops: {
        value: "catId",
        label: "name",
        children: "children",
      },
      // 控制分类显示方式：true显示完整路径，false显示末级名称
      showFullPath: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商品属性表格数据
      productAttrList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        attrName: null,
        searchType: null,
        icon: null,
        valueSelect: null,
        attrType: 0,
        enable: null,
        catelogId: null,
        showDesc: null,
        catelogPath: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
    };
  },
  created() {
    // 先获取分类树，再获取表格数据
    this.getCateGoryList()
      .then(() => {
        this.getList();
      })
      .catch((error) => {
        console.error("分类树加载失败，仍尝试获取表格数据：", error);
        this.getList();
      });
  },
  methods: {
    // 值类型切换时触发
    handleValueTypeChange() {
      this.isSingle = this.form.valueType === "单选";
      // 单选时，若可选项超过1个，只保留第一个
      if (this.isSingle && this.valueOptions.length > 1) {
        this.valueOptions = [this.valueOptions[0]];
        this.$message.warning("单选模式下，仅保留第一个可选项");
      }
    },
    // 添加选项
    addOption() {
      if (this.tempInput.trim()) {
        // 非空判断
        const value = this.tempInput.trim();
        if (!this.valueOptions.includes(value)) {
          // 去重
          // 单选模式且已有选项时，阻止添加
          if (this.isSingle && this.valueOptions.length >= 1) {
            this.$message.warning("单选模式下，只能添加一个可选项");
            this.tempInput = "";
            return;
          }
          this.valueOptions.push(value);
        }
        this.tempInput = ""; // 清空输入框
      }
    },
    // 删除选项
    removeOption(index) {
      this.valueOptions.splice(index, 1);
    },
    // 切换表格行分类显示方式
    toggleCategoryDisplay() {
      this.showFullPath = !this.showFullPath;
    },
    /** 查询商品属性列表 */
    getList() {
      this.loading = true;
      listProductAttr(this.queryParams).then((response) => {
        this.productAttrList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 获取所有商品分类
    getCateGoryList() {
      return new Promise((resolve, reject) => {
        listWithTree()
          .then((response) => {
            let rawData = response.rows || [];
            this.categoryList = this.filterTreeByShowStatus(rawData);
            resolve();
          })
          .catch((error) => {
            console.error("获取分类列表失败：", error);
            this.categoryList = [];
            reject(error);
          });
      });
    },
    // 递归过滤树形数据：移除showStatus=0的节点
    filterTreeByShowStatus(tree) {
      return tree
        .filter((node) => node.showStatus === 1) // 只保留showStatus=1的节点
        .map((node) => {
          // 对每个节点的children也进行递归过滤
          if (node.children && node.children.length > 0) {
            node.children = this.filterTreeByShowStatus(node.children);
          }
          return node;
        });
    },
    // 根据分类ID获取末级分类名称
    getCategoryName(data) {
      console.log("分类当前行", data);
      let catelogId = data.catelogId;
      if (!catelogId) return "未知分类";
      const findNode = (tree, id) => {
        for (const node of tree) {
          if (String(node.catId) === String(id)) {
            return node;
          }
          if (node.children && node.children.length > 0) {
            const found = findNode(node.children, id);
            if (found) return found;
          }
        }
        return null;
      };

      const node = findNode(this.categoryList, catelogId);
      return node ? node.name : "未知分类";
    },

    // 根据分类ID获取完整分类路径
    getCategoryFullPath(data) {
      let catelogId = data.catelogId;
      if (!catelogId) return "未知分类";

      const path = [];
      const findPath = (tree, id) => {
        for (const node of tree) {
          path.push(node.name);
          if (node.catId === id) {
            return true;
          }
          if (node.children && node.children.length > 0) {
            if (findPath(node.children, id)) {
              return true;
            }
          }
          path.pop();
        }
        return false;
      };

      const found = findPath(this.categoryList, catelogId);
      return found ? path.join("/") : "未知分类";
    },

    // 树节点点击
    handleTreeNodeClick(data, node, component) {
      console.log("树节点信息", data);
      this.loading = true;
      listSaleAttr({
        catelogId: data.catId,
        attrType: 1,
      }).then((response) => {
        this.productAttrList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        attrId: null,
        attrName: null,
        searchType: null,
        icon: null,
        valueSelect: null,
        attrType: null,
        enable: null,
        catelogId: null,
        showDesc: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      if (
        this.queryParams.catelogPath &&
        this.queryParams.catelogPath.length > 0
      ) {
        this.queryParams.catelogId =
          this.queryParams.catelogPath[this.queryParams.catelogPath.length - 1];
      } else {
        this.queryParams.catelogId = null; // 空值时，将 catelogId 置为 null（后端通常识别 null 为“不筛选”）
      }
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.attrId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.form.valueType = "单选"; // 新增时默认选中“单选”
      this.title = "添加商品属性";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const attrId = row.attrId || this.ids;
      getProductAttr(attrId).then((response) => {
        this.form = response.data;
        // 转换 valueType：0 → "单选"，1 → "多选"
        this.form.valueType = this.form.valueType === 0 ? "单选" : "多选";
        // 回显可选项：将逗号分隔的字符串转为数组
        this.valueOptions = this.form.valueSelect
          ? this.form.valueSelect.split(";").map((item) => item.trim())
          : [];
        // 同步值类型的单选/多选状态
        this.isSingle = this.form.valueType === "单选";
        this.open = true;
        this.title = "修改商品属性";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        this.form.catelogId =
          this.form.catelogPath[this.form.catelogPath.length - 1];
        // 转换 valueType："单选" → 0，"多选" → 1
        this.form.valueType = this.form.valueType === "单选" ? 0 : 1;
        // 将可选项数组转为逗号分隔的字符串（根据后端需求调整）
        this.form.valueSelect = this.valueOptions.join(";");
        if (valid) {
          if (this.form.attrId != null) {
            updateProductAttr(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addProductAttr(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const attrIds = row.attrId || this.ids;
      this.$modal
        .confirm('是否确认删除商品属性编号为"' + attrIds + '"的数据项？')
        .then(function () {
          return delProductAttr(attrIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "cloudmallproduct/productAttr/export",
        {
          ...this.queryParams,
        },
        `productAttr_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>

<style scoped>
/* 可选项列文字省略样式 */
.value-select-cell {
  white-space: nowrap; /* 不换行 */
  overflow: hidden; /* 超出部分隐藏 */
  text-overflow: ellipsis; /* 显示省略号 */
  max-width: 150px; /* 最大宽度，可根据需要调整 */
  padding: 0 5px; /* 适当留白 */
  text-align: left; /* 文字左对齐 */
}

/* 鼠标悬停时显示完整内容（可选） */
.value-select-cell:hover {
  overflow: visible;
  white-space: normal;
  z-index: 10;
  background-color: #fff;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 5px;
  max-width: 300px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  text-align: left; /* 悬停时文字也左对齐 */
}
</style>